<template>
  <section>
    <el-row
      :gutter="10"
      class="step_user"
      ref="step_user"
      :style="{
        display: 'flex',
        'align-items': 'center',
        'justify-content': 'center'
      }"
      v-if="runSelect"
    >
      <el-col :span="10" style="min-width: 300px;">
        <el-input placeholder="输入关键字查询" v-model="filterText"> </el-input>
        <div
          class="border_node_btn"
          style="margin-top: 10px"
          :style="{ height: height }"
        >
          <el-tree
            :key="users.length"
            :data="users"
            :show-checkbox="isMulSelect"
            :default-expand-all="defaultExpandAll"
            node-key="id"
            ref="tree"
            class="left_tree"
            :filter-node-method="filterNode"
            highlight-current
            :expand-on-click-node="false"
            @node-click="nodeClick"
            @check-change="leftCheckChange"
            :props="defaultProps"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <i :class="icoClass(data)"></i
              ><span style="margin-left: 5px;">{{ data.name }}</span>
            </span>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="4" style=" max-width:65px;display: table;">
        <div class="flex_box">
          <el-button
            :type="leftSelectNode !== null ? 'primary' : 'info'"
            @click="confirmSelectUser"
            :class=""
            style="margin-top: 10px;margin-left: 0px;"
            :disable="leftSelectNode === null"
            icon="el-icon-arrow-right"
          >
          </el-button>
          <el-button
            :type="rightSelectNode !== null ? 'primary' : 'info'"
            style="margin-top: 10px;margin-left: 0px;"
            @click="delSelectUser"
            :disable="rightSelectNode === null"
            icon="el-icon-arrow-left"
          >
          </el-button>
          <el-button
            type="primary"
            @click="allSelect"
            v-show="isMulSelect"
            :type="containUser === 0 ? 'primary' : 'info'"
            style="margin-top: 10px;margin-left: 0px;"
            icon="el-icon-caret-right"
          >
          </el-button>
          <el-button
            type="primary"
            style="margin-top: 10px;margin-left: 0px;"
            icon="el-icon-caret-left"
            :type="rightSelectUsers.length > 0 ? 'primary' : 'info'"
            @click="clearSelect"
          >
          </el-button>
        </div>
      </el-col>
      <el-col :span="rightSpan" ref="rightContent" :style="rightStyle">
        <div
          class="border_node_btn"
          style="margin-top: 10px"
          :style="{ height: height }"
        >
          <el-tree
            :data="rightSelectUsers"
            default-expand-all
            node-key="id"
            ref="rightTree"
            class="rightTree"
            highlight-current
            @node-click="nodeRightClick"
            :props="defaultRightProps"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <i :class="icoClass(data)"></i
              ><span style="margin-left: 5px;">{{ data.name }}</span>
              <span
                v-if="data.type !== 'org'"
                style="margin-left: 10px;color:#cececd "
                >{{ data.deptName ? data.deptName : data.workGroupName }}</span
              >
              <span
                style="margin-left: 10px;color:#cececd "
                v-if="containUser === 1 && data.type === 'org'"
                >{{ getCurNodeChildrenCount(data) }}人</span
              >
            </span>
          </el-tree>
        </div>
      </el-col>
    </el-row>
    <el-row v-else class="node_item">
      {{ userNames }}
    </el-row>
  </section>
</template>

<script>
import ArrayUtil from "@/libs/ArrayUtil";
import _ from "lodash";

export default {
  name: "user-select",
  props: {
    value: "",
    height: {
      type: [String],
      default: "190px"
    },
    width: {
      type: String,
      default: "50%"
    },
    title: {
      type: String,
      default: "选择组织机构和人员"
    },
    btnLabel: {
      type: String,
      default: "选择"
    },
    placeholder: {
      type: String,
      default: "请选择"
    },
    // 业务编码 null 使用页面属性的配置，否则根据key查询相应的配置
    businessKey: {
      type: String,
      default: null
    },
    // 用户范围
    userRange: {
      type: String,
      default: null
    },
    // 是否包含用户 0 不含，1包含
    containUser: {
      type: Number,
      default: 1
    },
    // 是否多选
    isMulSelect: {
      type: Boolean,
      default: false
    },
    // 是否允许选择
    runSelect: {
      type: Boolean,
      default: true
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    // 选择类型 0-部门/工作组，用户，1-用户，2-部门/工作组
    selectType: {
      type: Number,
      default: 0
    },
    // tab 配置
    tabConfig: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      isLoad: true, // 是否初始化加载
      userNames: "",
      userIds: "",
      rightCondition: "",
      rightSpan: 10,
      defaultProps: {
        children: "children",
        label: "name"
      },
      defaultRightProps: {
        children: "list",
        label: "name"
      },
      defaultExpandAll: false,
      activeName: "All",
      totalCount: 0,
      sortDialogVisible: false,
      searchCondition: {
        keyword: ""
      },
      users: [],
      rightSelectUsers: [], // 右侧选择的用户机构列表
      leftSelectNode: null, // 左侧点击选择对象
      rightSelectNode: null, // 右侧点击选择对象
      tabConfigData: {
        showAllOrganize: true,
        showCustomOrganize: false,
        customOrganizeId: 0,
        showAllWorkGroup: false,
        showPersonalWorkGroup: false,
        showAllOrganizeName: "全部",
        showCustomOrganizeName: "公文传输",
        showAllWorkGroupName: "工作组",
        showPersonalWorkGroupName: "我的工作组"
      },
      filterText: "" // 搜索树组件
    };
  },
  // model: {
  //   prop: 'userIds',
  //   event: 'returnBack'
  // },
  computed: {
    rightStyle() {
      return { "align-self": "flex-end" };
      // let me = this;
      // let span = 10;
      // this.$nextTick(function () {
      // let dialog = me.$refs.step_user.$el
      // let dialogBody = dialog.getElementsByClassName('step_user')
      // let bodyWidth = dialogBody[0].clientWidth
      // let one = (bodyWidth / 24)
      // span = (bodyWidth - (one * 10 + 90)) / one
      // me.rightSpan = Math.floor(span)
      // me.$refs.rightContent.$el.style.width = Math.floor(bodyWidth - (one * 10 + 65) - 20) + "px"
      // if (me.isMulSelect) {
      //   // 设置左侧勾选状态
      //   console.log(me.$refs, me.$refs['tree'])
      //   this.$refs.tree.setCheckedNodes([])
      //   this.$refs.tree.setCheckedNodes(this.rightSelectUsers)
      // }
      // })
    }
  },
  mounted() {
    // console.log(this.userRange, 'userRange')
    // console.log(this.$refs.tree,'ref.tree')
    if (this.runSelect) {
      this.getTabConfig();
    }
    if (this.value) {
      // console.log(this.value);
      if (this.value && this.value.length > 0) {
        this.userIds = this.value;
        // if (this.isLoad) {
        //   this.updateDefaultUser();
        // }
      }
    }
  },
  updated() {
    // if (this.value) {
    //   console.log(this.$refs.tree.getNode(this.value),'value')
    //   if (this.$refs.tree.getNode(this.value)) {
    //     // this.leftCheckChange(this.$refs.tree.getNode(this.value).data, true, false)
    //   }
    // }
  },
  watch: {
    users: {
      handler(val) {
        // console.log(val,'用户数量')
        if (val.length == 1) {
          this.defaultExpandAll = true;
        }
        this.showDeflue();
      },
      deep: true
    },
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    rightSelectUsers: {
      handler(val) {
        // console.log(val, 'valvalval')
        // this.$nextTick(() => {
        //   let arr = [];
        //   val.map(item => {
        //     arr.push(item.id)
        //   })
        //   this.$refs.tree.setCheckedKeys(arr, true);
        // })
        // this.$emit('rightSelectUser', {select: val});
        this.updateUsers();
      },
      deep: true
    },
    value: {
      handler(val) {
        if (val && val.length > 0) {
          this.userIds = val;
          if (this.isLoad) {
            this.updateDefaultUser();
          }
        }
      },
      deep: true
    }
  },
  methods: {
    // 回显加载
    showDeflue() {
      let arr = [];
      arr = this.userIds.split(",");
      // console.log(arr,this.$refs.tree)
      // console.log(arr)
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(arr, false);
      });
    },
    // 根据业务编码获取tab的控制属性
    getTabConfig() {
      // console.log(this.userRange, 'userRange')
      // console.log('getTabConfig')
      if (
        this.userRange === null ||
        this.userRange === "" ||
        this.userRange === undefined
      ) {
        if (this.businessKey === null) {
          if (this.tabConfig) {
            Object.assign(this.tabConfigData, this.tabConfig);
          }
        } else {
          this.API.getModuleUserByKey({ key: this.businessKey }).then(res => {
            Object.assign(this.tabConfigData, res.data);
          });
        }
        if (this.tabConfigData.showAllOrganize) {
          this.getOrganizeUser();
        } else {
          if (this.tabConfigData.showCustomOrganize) {
            this.getOrganizeUser(this.tabConfigData.customOrganizeId);
          } else {
            if (this.tabConfigData.showAllWorkGroup) {
              this.getWorkGroupUser(0);
            } else {
              if (this.tabConfigData.showPersonalWorkGroup) {
                this.getWorkGroupUser(1);
              }
            }
          }
        }
      } else {
        this.getTreeListByIds();
      }
    },
    // 回显
    async updateDefaultUser() {
      // console.log('updateDefaultUser')
      this.userNames = "";
      this.rightSelectUsers = [];
      if (this.userIds) {
        // console.log(this.userIds, 'user')
        let tem = { type: this.containUser, parentId: 0 };
        await this.API.getOrganizeTree(tem).then(async res => {
          let users = this.userIds.split(",");
          if (users && res.data) {
            let otherUsers = [];
            users.map((item, index) => {
              let name = this.getUserNameById(res.data, item);
              if (name === undefined || name === null) {
                otherUsers.push(item);
              } else {
                if (index === users.length - 1 - otherUsers.length) {
                  this.userNames += name;
                } else {
                  this.userNames += name + ",";
                }
              }
            });
            if (otherUsers && otherUsers.length > 0) {
              await this.getNameByGroupData(otherUsers);
            }
          }
        });
      }
    },

    getNameByGroupData(otherUsers) {
      let temGroup = { type: this.containUser, parentId: 0, isMe: 0 };
      this.API.getWorkGroupTree(temGroup).then(res => {
        if (res.data) {
          otherUsers.map((item, index) => {
            let name = this.getUserNameById(res.data, item);
            if (index === otherUsers.length - 1) {
              this.userNames += name;
            } else {
              this.userNames += name + ",";
            }
          });
        }
      });
    },

    getUserNameById(data, item) {
      for (let i = 0; i < data.length; i++) {
        let user = data[i];
        // console.log(item)
        if (user.id === item) {
          this.rightSelectUsers.push(user);
          // console.log(this.rightSelectUsers, '默认用户数组')
          return user.name;
        } else {
          if (user.children !== undefined) {
            let result = this.getUserNameById(user.children, item);
            if (result) {
              return result;
            }
          } else {
            continue;
          }
        }
      }
    },

    // 获取当前节点的数量
    getCurNodeChildrenCount(data) {
      let tem = data.children.flatArr();
      let users = [];
      if (tem) {
        tem.map(item => {
          if (item.type !== "org") {
            users.push(item);
          }
        });
      }
      return users.length;
    },
    // 右侧过滤
    rightFilter() {
      this.$refs.rightTree.filter(this.rightCondition);
    },
    // 计算选择人数
    computeCount(val) {
      let tem = val.flatArr();
      let users = [];
      if (tem) {
        tem.map(item => {
          if (item.type !== "org") {
            users.push(item);
          }
        });
      }
      this.totalCount = users.length;
    },
    // 右侧树点击
    nodeRightClick(data, node, self) {
      this.rightSelectNode = data;
      // console.log(data)
    },
    //根据类型获取图标
    icoClass(val) {
      if (val.type === "org") {
        return "fa fa-folder";
      } else {
        return "fa fa-user";
      }
    },
    // 过滤用户
    searchUser() {
      this.$refs.tree.filter(this.searchCondition.keyword);
    },
    // 获取组织用户
    getTreeListByIds() {
      /*
          判断默认处理者与选择范围是否有重复
          传部门ID的情况未处理
        * */
      let tem = {};
      if (this.value) {
        let valueArr = this.value.split(",");
        let userRangeArr = this.userRange.split(",");
        let noRepeatArr = [];
        noRepeatArr = userRangeArr;
        valueArr.map((item, index) => {
          //未重复的放到一个新数组
          // console.log(item)
          // console.log(userRangeArr)
          userRangeArr.findIndex(target => target == item) === -1 &&
            noRepeatArr.push(item);
        });
        let str = noRepeatArr.join(",");
        // console.log(str,'||||||',this.userRange)
        tem = { ids: this.userRange };
      } else {
        tem = { ids: this.userRange };
      }
      // let tem = {ids: this.userRange + (this.value !== '' ? ',' + this.value : '')}
      this.API.getTreeListByIds(tem).then(res => {
        this.users = res.data;
      });
    },
    // 获取组织用户
    getOrganizeUser(parentId) {
      let tem = {
        type: this.containUser,
        parentId: parentId === undefined ? 0 : parentId
      };
      this.API.getOrganizeTree(tem).then(res => {
        this.users = res.data;
      });
    },
    // 获取工作组用户
    getWorkGroupUser(isMe) {
      let tem = { type: this.containUser, parentId: 0, isMe: isMe };
      this.API.getWorkGroupTree(tem).then(res => {
        this.users = res.data;
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // tab切换
    handleClick(val) {
      // console.log(val)
      this.activeName = val.name;
      switch (val.name) {
        case "All":
          this.getOrganizeUser();
          break;
        case "Ann":
          this.getOrganizeUser(this.tabConfigData.customOrganizeId);
          break;
        case "WorkGroup":
          this.getWorkGroupUser(0);
          break;
        case "MyWorkGroup":
          this.getWorkGroupUser(1);
          break;
      }
    },
    // 树点击事件
    nodeClick(data, node, self) {
      this.leftSelectNode = data;
    },
    //左侧多选事件
    leftCheckChange(data, self, node) {
      // console.log(self);
      // if (!self) {
      //   this.rightSelectUsers.map((rightUser, index) => {
      //     if (rightUser.id === data.id) {
      //       // console.log(data.id,data.id,index)
      //       this.rightSelectUsers.splice(index, 1);
      //     }
      //   });
      // } else {
        let checkNodes = this.$refs.tree.getCheckedNodes();
        this.rightSelectUsers = _.cloneDeep(checkNodes);
        let orgs = [];
        this.rightSelectUsers.map((item,index)=>{
          if(item.type == 'org'){
            orgs.push(item)
          }
        })
        let arr = [];
        this.rightSelectUsers.map((item,index)=>{
          let status = true;
          orgs.map((item2,index2)=>{
            if(item2.origId == item.pid){
              status = false;
            }
          })
          if(status){
            arr.push(item)
          }
        })
        this.rightSelectUsers = arr;
      // }

      return;
      //如果取消选择，右侧去掉相关数据
      if (!self) {
        this.rightSelectUsers.map((rightUser, index) => {
          if (rightUser.id === data.id) {
            this.rightSelectUsers.splice(index, 1);
          }
        });
      }
      let depts = [];
      this.$refs.tree.getCheckedNodes().map(item => {
        if (item.type !== "user") {
          depts.push(item);
        }
      });
      this.$refs.tree.getCheckedNodes().map(item => {
        if (item.type === "user") {
          let existed = this.removeExistedUser(depts, item);
          if (!existed) {
            if (this.rightSelectUsers) {
              let existed = false;
              this.rightSelectUsers.map(rightUser => {
                if (rightUser.id === item.id) {
                  existed = true;
                }
              });
              if (!existed) {
                this.rightSelectUsers.push(item);
              }
            }
          }
        } else {
          if (this.rightSelectUsers) {
            let existed = false;
            this.rightSelectUsers.map(rightUser => {
              if (rightUser.id === item.id) {
                existed = true;
              }
            });
            if (!existed) {
              this.rightSelectUsers.push(item);
            }
          }
        }
      });
      // 右侧数据在去重复一次
      this.rightSelectUsers.map(item => {
        if (item.type !== "user") {
          depts.push(item);
        }
      });
      this.rightSelectUsers.map((item, index) => {
        if (item.type === "user") {
          let existed = this.removeExistedUser(depts, item);
          if (existed) {
            this.rightSelectUsers.splice(index, 1);
          }
        }
      });
    },

    // 递归遍历右侧选择的用户和部门以及部门下的子集，去除重复数据
    removeExistedUser(data, item) {
      let existed = false;
      if (data) {
        data.map(rightUser => {
          if (rightUser.id === item.id) {
            existed = true;
          } else {
            if (rightUser.children) {
              existed = this.removeExistedUser(rightUser.children, item);
            }
          }
        });
      }
      return existed;
    },
    // 展示用户弹出
    showUserDialog() {
      this.sortDialogVisible = true;
    },
    // 全选
    allSelect() {
      this.rightSelectUsers = _.clone(this.users);
      this.$refs.tree.setCheckedNodes(this.users);
    },
    // 清空
    clearSelect() {
      this.rightSelectUsers = [];
      this.$refs.tree.setCheckedNodes([]);
    },
    // 确认选择的用户
    confirmSelectUser() {
      if (this.leftSelectNode) {
        if (this.selectType === 1 && this.leftSelectNode.type !== "user") {
          this.warning("只能选择用户");
          return;
        }
        if (this.selectType === 2 && this.leftSelectNode.type === "user") {
          this.warning("请选择工作组或机构");
          return;
        }
        if (!this.isMulSelect && this.rightSelectUsers.length > 0) {
          this.warning("只允许选择一个用户");
          return;
        }

        let arr = this.$refs.tree.getCheckedNodes();
        arr.push(this.leftSelectNode);
        this.$refs.tree.setCheckedNodes(arr, true);
        let i = this.rightSelectUsers.indexOf(this.leftSelectNode);
        // console.log(i)
        if (i !== -1) {
          this.warning(this.leftSelectNode.name + ",已存在相同数据");
        } else {
          this.rightSelectUsers.push(this.leftSelectNode);
          this.leftSelectNode = null;
        }
      }
    },
    // 删除选择的用户
    delSelectUser() {
      if (this.rightSelectNode) {
        let arr = this.$refs.tree.getCheckedNodes();
        /*如果删除的类型是部门
         * 把左侧包含本部门Id的选中节点删除*/
        if (this.rightSelectNode.type == "org") {
          let arr1 = arr.filter(
            item1 => !item1.id.includes(this.rightSelectNode.id)
          );
          this.$refs.tree.setCheckedNodes(arr1, true);
        } else {
          let index = arr.findIndex(
            item => item.id === this.rightSelectNode.id
          );
          arr.splice(index, 1);
          this.$refs.tree.setCheckedNodes(arr, true);
        }
        let i = this.rightSelectUsers.indexOf(this.rightSelectNode);
        this.rightSelectUsers.splice(i, 1);
        this.rightSelectNode = null;
      }
    },
    // 跟新组件值
    updateUsers() {
      let val = "";
      this.userNames = "";
      if (this.rightSelectUsers) {
        this.rightSelectUsers.map((item, index) => {
          if (index === this.rightSelectUsers.length - 1) {
            this.userNames += item.name;
            val += item.id;
          } else {
            this.userNames += item.name + ",";
            val += item.id + ",";
          }
        });
      }
      // let arr = [];
      // val.split(",").map(item => {
      //   arr.push(item)
      // })
      // this.$refs.tree.setCheckedKeys(arr, true);
      // console.log(val, this.userNames, "更新input")
      this.isLoad = false;
      this.$emit("input", val);
      this.sortDialogVisible = false;
    }
  }
};
</script>

<style lang="less" scoped>
.node_item {
  line-height: 50px !important;
  height: 50px !important;
}

.flex_box {
  display: flex;
  flex-wrap: wrap;
}

.el-tree-node {
  white-space: normal;
}

.left_tree {
  /deep/ .el-tree-node__content > label.el-checkbox {
    position: relative !important;
    top: 0px !important;
  }
}
</style>
